<template>
  <div>
    <a-card :bordered="false" style="position: relative; margin-bottom: 10px">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper" style="position: relative">
        <div class="search-wrapper-btn">
          <a-button type="link" @click="show = !show">
            <span v-if="!show">展开<a-icon type="down" /></span>
            <span v-else>收起<a-icon type="up" /></span>
          </a-button>
        </div>
        <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol" @keyup.enter.native="onQuery">
          <div class="mode_item mode_item_none">
            <a-form-model-item label="告警时间" class="zdy-form-item-label">
              <a-range-picker
                :allowClear="true"
                v-model="rangePickerTime"
                valueFormat="YYYY-MM-DD"
                @change="rangePickerChange"
              />
            </a-form-model-item>
          </div>
          <div class="mode_item mode_item_none" v-show="show">
            <a-form-model-item label="告警类型" class="zdy-form-item-label">
              <a-checkbox
                :indeterminate="indeterminateState"
                :checked="checkAllState"
                @change="onCheckAllChange($event)"
              >
                全部
              </a-checkbox>
              <j-multi-select-tag
                v-model="formData.category"
                dictCode="alarmType"
                type="checkbox"
                @change="onChange($event)"
              />
            </a-form-model-item>
          </div>
          <div class="mode_item" v-show="show">
            <a-form-model-item label="告警状态">
              <j-dict-select-tag v-model="formData.status" placeholder="请选择" dictCode="alarmStatus" />
            </a-form-model-item>
            <a-form-model-item label="告警任务">
              <a-input v-model="formData.name" placeholder="请输入" />
            </a-form-model-item>
          </div>
          <div style="margin-top: 20px">
            <a-form-model-item :wrapper-col="{ offset: 0 }" style="margin-bottom: 0">
              <a-button class="Indormation-list-CX" type="primary" @click="onQuery"> 查询 </a-button>
              <a-button class="Indormation-list-CX" style="margin-left: 10px" @click="onResetForm"> 重置 </a-button>
              <span>
                <a-button type="primary" style="margin: 0 10px" @click="saveConfig"> 保存配置 </a-button>
                <!-- <a-tooltip placement="leftTop">
                  <template slot="title">
                    <span>针对预警时间、劝阻状态、预警等级、处置方式的当前选择保存配置</span>
                  </template>
                  <a-icon type="question-circle" />
                </a-tooltip> -->
              </span>
            </a-form-model-item>
          </div>
        </a-form-model>
      </div>
    </a-card>
    <a-card :bordered="false">
      <!-- 操作按钮区域 -->
      <div style="margin-bottom: 20px">
        <a-button type="primary" @click="onAdd()">新增告警配置</a-button>
        <!-- <a-button @click="onExport()" style="margin-left: 20px">导出</a-button> -->
      </div>
      <!-- 表格展示 -->
      <div class="table-page-content">
        <custom-table
          ref="table"
          rowKey="warningEvtid"
          :showColSettings="true"
          :hideColSettings="['action']"
          :showAlert="false"
          :showSelection="true"
          :loading="loading"
          :columns="columns"
          :dataSource="pageData"
          @selectedRow="onSelectedRow"
          @change="onTableChange"
        >
          <template v-slot:colSettings>
            <a-button class="table-custom-cols"> 字段配置 </a-button>
          </template>
          <template slot="category" slot-scope="text">
            <span v-if="text == '1'">区域告警</span>
            <span v-if="text == '2'">物品告警</span>
            <span v-if="text == '3'">账户告警</span>
            <span v-if="text == '4'">网站告警</span>
          </template>
          <template slot="status" slot-scope="text">
            <span class="text_color_1" v-if="text == '0'">待开始</span>
            <span class="text_color_2" v-if="text == '1'">有效</span>
            <span class="text_color_3" v-if="text == '2'">无效</span>
          </template>
          <template slot="warningTime" slot-scope="text, record">
            <span>{{ record.warnBeginAt }} -- {{ record.warnEndAt }}</span>
          </template>
          <!--操作-->
          <template slot="action" slot-scope="text, record">
            <a-button @click="onEdit(record)" type="link" style="padding: 0">编辑</a-button>
          </template>
        </custom-table>
      </div>
      <!--弹窗区域 -->
      <!-- <HandleModal ref="handleModalId" /> -->
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import * as alarmApi from '@/api/alarm.js'
import { getXzqhList, getDictItemsFromCache } from '@/api/api'
import CustomTable from '@/components/zxd/Table/CustomTable'
// import HandleModal from './components/HandleModal'
export default {
  components: {
    CustomTable,
    // HandleModal,
    // DetailsModal
  },
  data() {
    return {
      moment,
      labelCol: { span: 5 },
      wrapperCol: { span: 18 },
      rangePickerTime: [],
      show: false,
      loading: false,
      visible: false,
      indeterminateState: false,
      isDisabled: true,
      reloading: false,
      dictOptions: getDictItemsFromCache('alarmType'), //告警类型-字典值
      selectKeys: [],
      formData: {},
      columns: [
        {
          title: '告警任务',
          dataIndex: 'name',
          width: 80,
          align: 'center',
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '告警类型',
          dataIndex: 'category',
          width: 140,
          align: 'center',
          scopedSlots: { customRender: 'category' },
        },
        {
          title: '告警时长/天',
          dataIndex: 'timeLength',
          width: 115,
          align: 'center',
          scopedSlots: { customRender: 'timeLength' },
        },
        {
          title: '告警状态',
          dataIndex: 'status',
          width: 60,
          align: 'center',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '告警时间',
          dataIndex: 'warningTime',
          width: 200,
          align: 'center',
          scopedSlots: { customRender: 'warningTime' },
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          width: 180,
          align: 'center',
        },
        {
          title: '操作',
          width: 100,
          align: 'center',
          dataIndex: 'action',
          // slots: { title: 'customIsAction' },
          scopedSlots: { customRender: 'action' },
        },
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData: [],
    }
  },
  computed: {
    checkAllState() {
      let bool = false
      let category =
        Object.keys(this.formData).length > 0 && this.formData.category ? this.formData.category.split(',') : []
      if (this.dictOptions.length === category.length) {
        bool = true
      }
      return bool
    },
  },
  created() {},
  async mounted() {
    await this.getConfig()
    // this.initForm()
    this.onQuery()
  },
  methods: {
    initForm() {
      this.$set(
        this.formData,
        'category',
        this.dictOptions
          .map((v) => {
            return v.value
          })
          .join(',')
      )
    },
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.formData = {}
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.rangePickerTime = []
      this.$nextTick(() => {
        // 重置行政区划
        // this.$refs.linkage.reload()
        this.reload()
      })
      this.initForm()
      this.refreshTable()
    },
    onSelectedRow(keys) {
      this.selectKeys = keys
      this.isDisabled = keys.length > 0 ? false : true
    },
    onTableChange(pagination, pageFilter, sorter) {
      let keyMap = { currentPage: 'pageNo' }
      let paginations = Object.keys(pagination).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = pagination[key]
        return newData
      }, {})
      this.pageFilter = Object.assign({}, this.pageFilter, paginations)
      this.refreshTable()
    },
    refreshTable() {
      let formData = Object.assign({}, this.formData, this.pageFilter)
      this.loading = true
      alarmApi
        .smuWarnConfigList(formData)
        .then((res) => {
          if (res.success) {
            this.pageData = res.result
            this.loading = false
            // this.$refs.table.onClearRowKeys()
          } else {
            this.loading = false
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    //导出
    onExport() {},
    //导出
    onAdd() {
      this.$router.push({
        path: '/smuggleAlarm/configurationAdd',
        query: {
          category: 1, //第一个，区域告警选中
        },
      })
    },
    // 详情
    onEdit(record) {
      this.$router.push({
        path: '/smuggleAlarm/configurationEdit',
        query: {
          id: record.id,
          category: record.category,
        },
      })
    },
    // 保存配置
    saveConfig() {
      let obj = {
        warnBeginAt: this.formData.warnBeginAt,
        warnEndAt: this.formData.warnEndAt,
        category: this.formData.category,
        name: this.formData.name,
        status: this.formData.status,
      }
      var parameter = {
        config: JSON.stringify(obj),
        modulePrefix: 'alarm_config',
      }
      alarmApi
        .saveQueryConfig(parameter)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.warn(res.message)
          }
        })
        .catch((e) => {
          this.$message.warn('请求失败！')
        })
    },
    // 获取保存配置
    async getConfig() {
      try {
        var parameter = {
          modulePrefix: 'alarm_config',
        }
        let res = await alarmApi.getQueryConfig(parameter)
        if (res.success) {
          let data = res.result && res.result != 'null' ? res.result : {}
          let parseData = Object.keys(data).length > 0 ? JSON.parse(data) : {}
          if (data && Object.keys(parseData).length > 0) {
            console.log("category")
            console.log(parseData.category)
            this.$set(this.formData, 'category', parseData.category)
            this.$set(this.formData, 'status', parseData.status)
            this.$set(this.formData, 'name', parseData.name)
            this.$set(this.formData, 'warnBeginAt', parseData.warnBeginAt)
            this.$set(this.formData, 'warnEndAt', parseData.warnEndAt)
            this.rangePickerTime = [parseData.warnBeginAt, parseData.warnEndAt]
          } else {
            this.initForm()
          }
        } else {
          this.initForm()
        }
      } catch (err) {
        this.$message.warn('请求失败！')
      }
    },
    // 预警时间
    rangePickerChange(date) {
      this.$set(this.formData, 'warnBeginAt', date[0])
      this.$set(this.formData, 'warnEndAt', date[1])
    },
    onCheckAllChange(e) {
      Object.assign(this, { indeterminateState: false })
      this.$set(
        this.formData,
        'category',
        e.target.checked
          ? this.dictOptions
              .map((v) => {
                return v.value
              })
              .join(',')
          : null
      )
    },
    onChange(checkedList) {
      let dataLists = checkedList.split(',')
      this.indeterminateState = !!dataLists.length && dataLists.length < this.dictOptions.length
    },
    /** 重新加载组件 */
    reload() {
      this.reloading = true
      this.$nextTick(() => (this.reloading = false))
    },
  },
}
</script>
<style lang="less" scoped>
.mode_item {
  display: flex;
  border-bottom: 1px #dadada dashed;
  > div {
    flex: 0 0 25%;
  }
  & > * {
    width: 100%;
    margin-bottom: 0;
    padding: 5px 0;
  }
  &.mode_item_none {
    > div {
      flex: inherit;
    }
  }
  .zdy-form-item-label {
    /deep/.ant-form-item-label {
      width: 70px;
    }
    &.xzqh-form-item-label {
      /deep/.ant-form-item-control-wrapper {
        .ant-form-item-children {
          display: -webkit-box;
        }
      }
      /deep/.area-select {
        // margin-top: 4px;
        line-height: 1;
      }
      /deep/.select-tag {
        width: 162px !important;
        margin-left: 10px;
        margin-top: 3px;
      }
      // /deep/.area-select .area-selected-trigger {
      //   line-height: 1.15;
      // }
      // /deep/.ant-select-lg .ant-select-selection--single{
      //   height: 34px;
      // }
      // /deep/.ant-select-lg .ant-select-selection__rendered {
      //   line-height: 34px;
      //   font-size: 14px;
      // }
    }
  }
}
.search-wrapper-btn {
  position: absolute;
  right: 0;
  top: 15px;
  z-index: 1;
}
/deep/.table-custom-cols {
  top: -48px !important;
}
.custom-ewm {
  padding: 14px;
  background-color: #fff;
  border: 1px #ccc solid;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
}
/deep/.ant-dropdown-menu-item {
  text-align: center;
  border-bottom: 1px #f5f5f5 solid;
  &:last-child {
    border-bottom: 0;
  }
}
/deep/.anticon.anticon-down {
  font-size: 14px !important;
}

.table-page-content {
  /deep/.ant-table-thead > tr > th,
  /deep/.ant-table-tbody > tr > td {
    padding-left: 0;
    padding-right: 0;
  }
  /deep/.ant-table-thead > tr:first-child > th:first-child,
  /deep/.ant-table-tbody > tr > td:first-child {
    padding-left: 10px;
  }
  .text_color_1 {
    color: #f59a23;
    padding-right: 6px;
  }
  .text_color_2 {
    color: #71B604;
    padding-right: 6px;
  }
  .text_color_3 {
    color: #d9001b;
    padding-right: 6px;
  }
}
</style>
